import Vue from 'vue'
import App from './App.vue'
import router from './router'
import Mint from 'mint-ui';
import Vuex from 'vuex'
import 'mint-ui/lib/style.css';
import './lib/dist/css/mui.css'
//导入格式化时间的插件
import moment from 'moment'
//import './lib/dist/js/mui'
import http from './http'
//定义全局的过滤器
Vue.filter('dateFormat',function(dataStr,pattern="YYYY-MM-DD HH:mm:ss"){
    return moment(dataStr).format(pattern)
})


Vue.prototype.$http = http
Vue.use(Mint);
Vue.use(Vuex);
Vue.config.productionTip = false
//在刚调用的时候从localstorage调用数据
var  car = JSON.parse(localStorage.getItem('car')||'[]')
const store = new Vuex.Store({
  state:{//this.$store.state.***
    car:car
  },
  mutations:{//this.$store.commit('方法的名称')
    addToCar(state,goodsinfos){
      //点击加入购物车把商品信息保存到car上
      var flag = false;

      state.car.some(item=>{
        if(item.id==goodsinfos.id){
          item.count+=parseInt(goodsinfos.count);
          flag=true;
          return true;
        }
      })

      if(!flag){
          state.car.push(goodsinfos)
      }
      //当更新car之后，把car数组存储到本地的localstorage
      localStorage.setItem('car',JSON.stringify(state.car)); 
    },
    updateGoodsInfo(state,goodsinfo){
      //修改购物车中商品的数
      state.car.some(item=>{
        if(item.id == goodsinfo.id){
          item.count = parseInt(goodsinfo.count)
          return true;
        }
      })
      localStorage.setItem('car',JSON.stringify(state.car)); 
    },
    removeFromCar(state,id){
      //根据id从store中删除对应数据
      state.car.some((item,i)=>{
        if(item.id == id){
          state.car.splice(i,1);
          return true;
        }
      })
      localStorage.setItem('car',JSON.stringify(state.car)); 
    },
    updateGoodsSelected(state,info){
      state.car.some(item=>{
        if(item.id == info.id){
          item.selected = info.selected
          return true;
        }
      })
      localStorage.setItem('car',JSON.stringify(state.car)); 
    }
  },
  getters:{//this.$store.getters.***
      getAllCount(state){
          var c =0;
          state.car.forEach(item=>{
            c+=item.count;
          })
          return c;
      },
      getGoodsCount(state){
        var o = {};
        state.car.forEach(item=>{
          o[item.id]=item.count;
        })
        return o;
      },
      getGoodsSelected(state){
        var o ={};
        state.car.forEach(item=>{
          o[item.id]=item.selected;
        })
        return o;
      },
      getGoodsCountAndAmount(state){
        var o ={
          count : 0,//勾选的数量
          amount : 0//勾选的总价
        };
        state.car.forEach(item=>{
          if(item.selected){
            o.count+=item.count;
            o.amount+=item.price*item.count;
          }
        })
        return o;
      }
  }
})

new Vue({
  router,
  store,//挂载store状态管理对象
  render: h => h(App)
}).$mount('#app')
